<template>
	<div class="Fibonacci">
		<canvas :ref="el => dataset.el = el">
			123
		</canvas>
	</div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import * as fibonacci from './utils.js'

const cloneCanvas = reactive({
	el: null,
	ctx: null
})
const dataset = reactive({
	el: null,
	ctx: null,
	height: 0,
	width: 0,
})

function init() {
	const { height, width } = getComputedStyle(dataset.el.parentElement)
	dataset.height = Number(height.split('px')[0])
	dataset.width = Number(width.split('px')[0])
	dataset.el.height = dataset.height
	dataset.el.width = dataset.width
	dataset.ctx = dataset.el.getContext('2d')
	
	cloneCanvas.el = dataset.el.cloneNode(true)
	cloneCanvas.ctx = cloneCanvas.el.getContext('2d')

	dataset.ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'
	dataset.ctx.fillRect(0, 0, dataset.el.width, dataset.el.height)
	requestAnimationFrame(drawGinkgo)
}

function clear(el, ctx) {
	ctx?.clearRect(0, 0, el.width, el.height)
}

function newCanvas() {
	const el = cloneCanvas.el.cloneNode(true)
	const ctx = el.getContext('2d')
	return { el, ctx }
}

/**
 * 
 * @param el
 * @param ctx
 * @param fn 绘制基本单元 ctx, i
 * @param len 数量
 * @param transProp 银杏[1, 0.11, -0.1, 1, 0, 0]
 */
function drawTransform(el, ctx, fn, len, transProp) {
	for(let i = 0; i < len; i++) {
		fn(ctx, i)
		ctx.transform(...transProp);
	}
}

function drawRotate(el, ctx, angle, fn) {
	ctx.save()
	console.log(angle)
	ctx.translate(el.width / 2, el.height / 2)
	ctx.rotate(angle*Math.PI/180);
	fn()
	ctx.restore()
}

function drawGinkgo() {
	const len = 18
	const colors = ['#71c71c', '#638e38', '#e38e38', '#f1c71b']
	const { el, ctx } = newCanvas()
	el.height = 620
	el.width = 600
	// 单位单元背景
	// ctx.fillStyle = 'blue'
	// ctx.fillRect(0, 0, el.width, el.height)
	for(let i = 0; i < 9; i++) {
		drawRotate(
			el, ctx,
			// 固定单元角度
			// 180,
			Math.random()*180,
			() => drawTransform(
				el, ctx,
				(ctx, i) => {
					ctx.fillStyle=colors[Math.floor(Math.random() * colors.length)];
					ctx.fillRect(0,0,250,25)
				},
				len,
				[1.01, 0.11, -0.1, 1, 0, 0]
			)
		)
		// 固定单元位置
		// dataset.ctx.drawImage(el, 500, 200)
		dataset.ctx.drawImage(el, Math.random()*dataset.el.width / 2, Math.random()*dataset.el.height / 2)
	}
}

onMounted(() => {
	init()
})
</script>

<style lang="scss">
.Fibonacci {
	position: fixed;
	inset: 100px;
	// & > canvas {
	// 	height: 100%;
	// 	width: 100%;
	// }
}
</style>